﻿namespace TradePublish.Service
{
    using TradePublish.Common;
     using TradePublish.Exceptions;
    using log4net;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Drawing;
    using System.Net;
    using System.Reflection;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using TradePublish.Entity;
    using Winista.Text.HtmlParser;
    using Winista.Text.HtmlParser.Filters;
    using Winista.Text.HtmlParser.Tags;
    using Winista.Text.HtmlParser.Util;

    public class AntiSearchTMManager
    {
        public string applyUserNameZh;
        public int classNo;
        private ILog log = null;
        private CookieContainer logc = null;
        public string regNo;
        public List<TradeNameSplit> tradeNames = new List<TradeNameSplit>();
        public int tradePublishId;

        public AntiSearchTMManager()
        {
            this.log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        }

        public List<AntiSearchResult> antiSearch(List<string[]> details)
        {
            List<AntiSearchResult> list = new List<AntiSearchResult>();
            for (int i = 0; i < this.tradeNames.Count; i++)
            {
                List<AntiSearchResult> list2;
                if (this.tradeNames[i].type == 0)
                {
                    //英文,反查各种条件情况下的注册号，内部异常自己处理
                    List<AntiSearchResult> r0 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "05", "换序");
                    List<AntiSearchResult> r1 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "01", "完全相同");
                    List<AntiSearchResult> r2 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "03", "减字母");
                    List<AntiSearchResult> r3 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "04", "变字母");

                    List<AntiSearchResult> r4 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "06", "部分相同");
                    List<AntiSearchResult> r5 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "10", "读音近似");
                    List<AntiSearchResult> r6 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "09", "百分之二十相似");
                    List<AntiSearchResult> r7 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "02", "任意位置加字母");
                    list.AddRange(r0);
                    list.AddRange(r1);
                    list.AddRange(r2);
                    list.AddRange(r3);
                    list.AddRange(r4);
                    list.AddRange(r5);
                    list.AddRange(r6);
                    list.AddRange(r7);
                    this.log.Info("英文反查" + this.tradeNames[i].key + "完毕.");
                }
                else if (this.tradeNames[i].type == 1)
                {
                    ////数字反查各种条件情况下的注册号，内部异常自己处理
                    //List<AntiSearchResult> r0 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "05", "换序");
                    //List<AntiSearchResult> r1 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "01", "完全相同");
                    //List<AntiSearchResult> r2 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "06", "部分相同");
                    //List<AntiSearchResult> r3 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "04", "变任一数字");
                    //list.AddRange(r0);
                    //list.AddRange(r1);
                    //list.AddRange(r2);
                    //list.AddRange(r3);
                    //this.log.Info("数字反查" + this.tradeNames[i].key + "完毕.");
                }
                else
                {
                    if ( tradeNames[i].key!= null && tradeNames[i].key.Trim().Length == 1)
                    {
                        continue;//只有一个汉字
                    }
                    //汉字反查各种条件情况下的注册号，内部异常自己处理
                    List<AntiSearchResult> r0 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "05", "换序");
                    List<AntiSearchResult> r1 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "01", "完全相同");
                    List<AntiSearchResult> r2 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "07", "读音");
                    List<AntiSearchResult> r3 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "02", "任意位置加汉字");

                    List<AntiSearchResult> r4 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "06", "部分相同");
                    List<AntiSearchResult> r5 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "03", "减汉字");
                    List<AntiSearchResult> r6 = getAntiResult(tradeNames[i].type, tradeNames[i].key, "04", "变汉字"); 

                    list.AddRange(r0);
                    list.AddRange(r1);
                    list.AddRange(r2);
                    list.AddRange(r3);

                    list.AddRange(r4);
                    list.AddRange(r5);
                    list.AddRange(r6);
                    this.log.Info("汉字反查" + this.tradeNames[i].key + "完毕.");
                }
            }
            if (list == null)
            {
                return null;
            }
            Hashtable hashtable = new Hashtable();
            for (int j = 0; j < list.Count; j++)
            {
                if (hashtable[list[j].detail[0x11]] == null)
                {
                    hashtable.Add(list[j].detail[0x11], list[j].detail[0x11]);
                }
            }
            this.log.Info("开始采集本次反查所查询出来的所有商标[共" + hashtable.Count + "个]详情.");
            int index1 = 0;
            foreach (System.Collections.DictionaryEntry item in hashtable)
            {
                String[] detail = null;
                while (true)
                {
                    try
                    {
                        log.Info("对反查商标进行采集,当前进度：" + index1 + "/" + hashtable.Count + ".");
                        detail = this.doGraspTMInfo(item.Key.ToString(), false);//采集详情,内部异常抛出
                        break;
                    }
                    catch (Exception e)
                    {
                        log.Error("采集商标[" + item.Key.ToString() + "]详情异常.", e);
                        Thread.Sleep(1000);
                        continue;
                    }
                }
                //所有是本商标的，都写一下
                for (int d = 0; d < list.Count; d++)
                {
                    if (list[d].detail[17].Equals(item.Key.ToString()))
                    {
                        if (detail != null)
                            list[d].detail = detail;

                        //过滤掉商标已无效、申请人名称<=3个字符、申请人名称（英文），有内容的
                        if (detail == null)
                        {
                            list[d].needSaveAntiSearch = false;// 
                        }
                        else
                        {
                            if (detail[16] != null && detail[16].IndexOf("商标已无效") >= 0
                                || detail[22] != null && detail[22].IndexOf("期满未续展") >= 0)
                            {
                                list[d].needSaveAntiSearch = false;//商标已无效
                            }
                            //if (  detail[2] == null || detail[2] != null && detail[2].Trim().Length < 4)
                            //{
                            //    rtn[d].needSaveAntiSearch = false;//申请人名称<=3个字符
                            //}
                            //if ( detail[4] != null && detail[4].Trim().Length > 0)
                            //{
                            //    rtn[d].needSaveAntiSearch = false;//申请人名称（英文） 有内容
                            //}
                            if (applyUserNameZh != null && detail[2] != null && applyUserNameZh.Equals(detail[2]))
                            {
                                list[d].needSaveAntiSearch = false;//申请人相同
                            }
                        }
                    }
                }
                //过滤掉商标已无效、申请人名称<=3个字符、申请人名称（英文），有内容的
                if (detail == null
                    || detail[16] != null && detail[16].IndexOf("商标已无效") >= 0
                    || detail[22] != null && detail[22].IndexOf("期满未续展") >= 0
                    || applyUserNameZh != null && detail[2] != null && applyUserNameZh.Equals(detail[2])
                    //|| detail[2] == null || detail[2] != null && detail[2].Trim().Length < 4
                    //|| detail[4] != null && detail[4].Trim().Length > 0
                    )
                {
                    ;//无效商标直接过滤掉
                }
                else
                {
                    details.Add(detail);
                }
                index1++;
            }
            return list;
        }

        /// <summary>
        /// 真正的采集并保存到数据库。
        /// </summary>
        /// detail[0] 国际分类号;
        /// detail[1] 申请日期;
        /// detail[2] 申请人名称_中文;
        /// detail[3] 申请人地址_中文;
        /// detail[4] 申请人名称_英文;
        /// detail[5] 申请人地址_英文;
        /// detail[6] 使用商品IP;
        /// detail[7] 初审公告期号;
        /// detail[8] 初审公告日期;
        /// detail[9 注册公告期号;
        /// detail[10 注册公告日期;
        /// detail[11 专用权期限;
        /// detail[12 代理人名称;
        /// detail[13 是否共有商标;
        /// detail[14 商标类型;
        /// detail[15 商标流程IP;
        /// detail[16] 备注; 
        /// detail[17] 注册号  -----
        /// detail[18] 商标名称（全部）  -----
        /// detail[19] 申请人2       -----
        /// detail[20] 申请人3       -----
        /// detail[21] 使用商品       -----
        /// detail[22] 商标流程       ----- 
        public String[] doGraspTMInfo(String arrayRegNo, bool needGraspPic)
        {
            if (logc == null)
            { //登录首页
                this.logc = getLoginCookie();
            }
            if (this.logc == null)
            {
                this.logc = getLoginCookie();
                throw new GraspTMException("登录异常"); //---------登录失败，抛出异常，结束。
            }
            #region  开始采集
            GraspHTML grasphtml = new GraspHTML();
            String source1 = grasphtml.getHTMLCode(Global.RegNo + arrayRegNo, this.logc);
            if (grasphtml.getException().Length > 0 || source1 == null || source1.Length == 0)
            {
                this.logc = getLoginCookie();
                throw new GraspTMException(grasphtml.getException());  //-----------------发生异常,抛出异常，结束。
            }
            if (source1.IndexOf("抱歉") > 0)
            {
                return null;//没有该商标的信息.
            }
            else if (source1.ToLower().IndexOf("javascript:window.open") > 0)
            {//找到商标了	 
                #region 得到 AllName 商标文字_临时
                Parser parserT = Parser.CreateParser(source1, "UTF-8"); ;
                NodeFilter filterT = new NodeClassFilter(typeof(Winista.Text.HtmlParser.Tags.ATag));
                NodeList nodesT = parserT.ExtractAllNodesThatMatch(filterT);
                string httpip = "";
                String AllName = "";
                int c = 0;
                for (int j = 0; j < nodesT.Size(); j++)
                {
                    Winista.Text.HtmlParser.Tags.ATag tag = (Winista.Text.HtmlParser.Tags.ATag)(nodesT.ElementAt(j) is ITag ? nodesT.ElementAt(j) as ITag : null);
                    if (tag != null && !tag.IsEndTag())
                    {
                        c++;
                        if (c != 3)
                        {
                            continue;
                        }

                        AllName = tag.LinkText;
                        AllName = AllName.Replace("\r", "");
                        AllName = AllName.Replace("\n", "");
                        AllName = AllName.Replace("\t", "");
                        AllName = AllName.Replace("&nbsp;", " ");
                        httpip = tag.GetAttribute("onclick");//javascript:window.open('/trade/servlet?Search=TI_REG&amp;RegNO=3453422&amp;IntCls=25&amp;iYeCode=0

                        MatchCollection mc = Regex.Matches(httpip, @"open\('[^']+'", RegexOptions.IgnoreCase);
                        foreach (Match mt in mc)
                        {
                            httpip = mt.Value.Substring(6, mt.Value.Length - 7);
                            break;
                        }
                        httpip = httpip.Replace("&amp;", "&");
                        httpip = Global.Detial + httpip;
                    }
                }
                #endregion

                source1 = grasphtml.getHTMLCode(httpip, this.logc);
                if (grasphtml.getException().Length > 0 || source1 == null || source1.Length == 0 || source1.IndexOf("请从首页访问") > 0)
                {
                    #region  没登录 ，抛异常
                    this.logc = null;
                    throw new GraspTMException("Session超时，需要重新登录"); //---------Session超时，需要重新登录。
                    #endregion
                }

                String[] detial = GetDetial(source1);//拆分成各个字段
                detial[17] = arrayRegNo;
                detial[18] = AllName;

                #region 继续采集申请人2、申请人3
                String 申请人2 = "";
                String 申请人3 = "";
                String temp1 = "";
                String temp2 = "";
                if (detial[13].Equals("是"))
                {
                    source1 = grasphtml.getHTMLCode(Global.Applay, this.logc);
                    if (grasphtml.getException().Length > 0 || source1 == null || source1.Length == 0)
                    {
                        #region  没登录，抛异常
                        this.logc = null;
                        throw new GraspTMException("Session超时，需要重新登录"); //---------Session超时，需要重新登录。
                        #endregion
                    }
                    source1 = source1.Substring(source1.IndexOf("名称"));
                    source1 = source1.Substring(source1.ToLower().IndexOf("<td") + 5);
                    source1 = source1.Substring(source1.IndexOf(">") + 1);
                    temp1 = source1.Substring(0, source1.ToLower().IndexOf("</td"));
                    if (temp1.IndexOf("1") > 0)
                    {
                        #region  拆分，得到申请人2、3
                        source1 = source1.Substring(source1.ToLower().IndexOf("<td") + 1);
                        source1 = source1.Substring(source1.IndexOf(">") + 1);
                        temp1 = source1.Substring(0, source1.ToLower().IndexOf("</td"));
                        source1 = source1.Substring(source1.ToLower().IndexOf("<tr") + 5);
                        source1 = source1.Substring(source1.IndexOf(">") + 1);
                        temp2 = source1.Substring(0, source1.ToLower().IndexOf("</td"));
                        if (temp2.IndexOf("2") > 0)
                        {
                            source1 = source1.Substring(source1.ToLower().IndexOf("<td") + 1);
                            source1 = source1.Substring(source1.IndexOf(">") + 1);
                            temp2 = source1.Substring(0, source1.ToLower().IndexOf("</td"));
                        }
                        temp1 = RemoveCode(temp1);
                        temp1 = temp1.Replace(" ", "");
                        temp2 = RemoveCode(temp2); ;
                        temp2 = temp2.Replace(" ", "");
                        申请人2 = temp1; 申请人3 = temp2;
                        #endregion
                    }
                    temp1 = "";
                    temp2 = "";
                }
                detial[19] = 申请人2;
                detial[20] = 申请人3;
                #endregion

                #region  继续采集使用商品detial[6]
                String 使用商品 = "";

                detial[6] = detial[6].Replace("search=sx_selectgs&regno=", "Search=SX_SelectGS&RegNO=");
                detial[6] = detial[6].Replace("intcls", "IntCls");
                source1 = grasphtml.getHTMLCode(Global.Liucheng + detial[6], this.logc);
                if (grasphtml.getException().Length > 0 || source1 == null || source1.Length == 0)
                {
                    #region  没登录，抛异常
                    this.logc = null;
                    throw new GraspTMException("Session超时，需要重新登录"); //---------Session超时，需要重新登录。
                    #endregion
                }
                HTMLTable dd = new HTMLTable(source1);
                Hashtable leisi = new Hashtable();
                ArrayList keys = new ArrayList();
                int beginrowindex = 2;
                String contentStr = "";
                String leisiqunNo = "";
                String xuhao = "";
                while (true)
                {
                    if (dd.rows.Count <= beginrowindex)
                    {
                        break;
                    }
                    xuhao = ((String)(((ArrayList)(dd.rows[beginrowindex]))[0])).Replace("&nbsp;", "");
                    int xuhaoi = 0;
                    try
                    {
                        xuhaoi = Convert.ToInt32(xuhao);
                    }
                    catch (Exception)
                    {
                        xuhaoi = 0;
                    }
                    if (xuhaoi > 0)
                    {//有本行
                        contentStr = ((String)(((ArrayList)(dd.rows[beginrowindex]))[1])).Replace("&nbsp;", "");
                        contentStr = contentStr.Replace(" ", "");
                        leisiqunNo = ((String)(((ArrayList)(dd.rows[beginrowindex]))[2])).Replace("&nbsp;", "");
                        leisiqunNo = leisiqunNo.Replace(" ", "");
                        if (leisi.ContainsKey(leisiqunNo))
                        {
                            leisi[leisiqunNo] += contentStr + ";";
                        }
                        else
                        {
                            leisi.Add(leisiqunNo, contentStr + ";");
                            keys.Add(leisiqunNo);
                        }
                    }
                    else
                    {
                        break;
                    }
                    beginrowindex++;
                }
                for (int ii = 0; ii < keys.Count; ii++)
                {
                    String key = "" + keys[ii];
                    使用商品 += "[" + key + "——" + leisi[key] + "] ";
                }
                detial[21] = 使用商品;
                //"[3005——螺旋藻(非医用营养品);非医用营养粉;非医用营养胶囊;非医用营养片;非医用营养液;非医用营养膏;]\n[3001——作咖啡代用品的植物制剂;]\n[3002——茶叶代用品;]\n"

                #endregion

                #region 继续采集商标流程
                String 商标流程 = "";
                detial[15] = detial[15].Replace("search=fl_reg&regno=", "Search=FL_REG&RegNO=");
                detial[15] = detial[15].Replace("intcls", "IntCls");
                source1 = grasphtml.getHTMLCode(Global.Liucheng + detial[15], this.logc);
                if (grasphtml.getException().Length > 0 || source1 == null || source1.Length == 0)
                {
                    #region  没登录，抛异常
                    this.logc = null;
                    throw new GraspTMException("Session超时，需要重新登录"); //---------Session超时，需要重新登录。
                    #endregion
                }
                String mm = "";
                if (source1 != null && source1.Length > 0 && source1.ToLower().IndexOf("商标状态") > 0)
                {
                    source1 = source1.Substring(source1.ToLower().IndexOf("时间"));
                    int vv = 0;
                    while (source1.ToLower().IndexOf("colspan=\"2\"") > 0)
                    {
                        source1 = source1.Substring(source1.ToLower().IndexOf("colspan=\"2\""));
                        source1 = source1.Substring(source1.IndexOf(">") + 1);
                        mm = source1.Substring(0, source1.ToLower().IndexOf("</td"));
                        mm = RemoveCode(mm);
                        mm = mm.Replace(" ", "");
                        商标流程 += (vv > 0 ? "--->" : "") + mm;

                        source1 = source1.Substring(source1.ToLower().IndexOf("colspan=\"2\""));
                        source1 = source1.Substring(source1.ToLower().IndexOf(">") + 1);
                        mm = source1.Substring(0, source1.ToLower().IndexOf("</td"));
                        mm = RemoveCode(mm);
                        mm = mm.Replace(" ", "");
                        商标流程 += "(" + mm + ")";
                        vv++;
                    }
                    if (商标流程.IndexOf("没有符合条件的查询结果！") >= 0)
                    {
                        商标流程 = "";
                    }
                    else if (商标流程.IndexOf("商标已无效()") >= 0)
                    {
                        商标流程 = 商标流程.Replace("()", "");
                    }
                }
                detial[22] = 商标流程;
                #endregion

                #region //继续采集商标图片,并保存。
                //if(needGraspPic)
                //{
                //    bool hasGraspPic=isHasGraspPic(arrayRegNo);
                //    if (!hasGraspPic)
                //    {//未采集过的情形下才采集
                //        String url="http://sbcx.saic.gov.cn/trade/pictureservlet3?RegNO="+arrayRegNo+"&IntCls="+detial[0] ;//继续抓内页。						
                //        #region 继续采集商标图片
                //        byte[] buffer;
                //        try
                //        {
                //            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);//继续抓内页。
                //            myReq.CookieContainer = logc;
                //            HttpWebResponse resp = myReq.GetResponse() as HttpWebResponse;

                //            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream(), System.Text.Encoding.Unicode);
                //            buffer = System.Text.Encoding.Unicode.GetBytes(sr.ReadToEnd());


                //            resp.Close();
                //        }
                //        catch (Exception ee)
                //        {
                //            throw new GraspTMException("保存商标图片时发生异常：" + ee.Message);
                //        }
                //        #region  将图片存入数据库中。
                //        SqlConnection connection = new SqlConnection(Global.DBLinkStrSQL);
                //        try
                //        {
                //            connection.Open();
                //            SqlCommand cmd = null;
                //            if (hasGraspPic)
                //            {
                //                cmd = new SqlCommand("update BRAND_IMAGE   set IMAGEDATA=@pic ,ISNORMAL=0   where REGNO=@text ", connection);
                //            }
                //            else
                //            {
                //                cmd = new SqlCommand("insert into BRAND_IMAGE   values (@pic, @text,0)", connection);
                //            }
                //            cmd.Parameters.Add("@pic", buffer);
                //            cmd.Parameters.Add("@text", arrayRegNo);
                //            cmd.ExecuteNonQuery();
                //            connection.Close();
                //        }
                //        catch (Exception ee)
                //        {
                //            if (connection.State == ConnectionState.Open)
                //            { connection.Close(); }
                //            throw new GraspTMException("保存商标图片时发生异常：" + ee.Message);
                //        }
                //        #endregion
                //        #endregion 
                //    }
                //}
                #endregion


                return detial;


            }
            else if (source1.ToLower().IndexOf("error") > 0)
            {
                #region  没登录 ，抛异常
                this.logc = null;
                throw new GraspTMException("Session超时，需要重新登录"); //---------Session超时，需要重新登录。
                #endregion
            }
            else
            {
                #region 其他错误，抛异常
                throw new GraspTMException("其他错误"); //其他错误。
                #endregion
            }
            #endregion
        }


        private List<AntiSearchResult> getAntiResult(int searchType, string keyword, string searchConditionCode, string searchCondition)
        {
            List<AntiSearchResult> list = new List<AntiSearchResult>();
            List<string> list2 = this.getRegNos(this.classNo, searchType, keyword, searchConditionCode);
            if ((list2 != null) && (list2.Count != 0))
            {
                Hashtable hashtable = new Hashtable();
                for (int i = 0; i < list2.Count; i++)
                {
                    if (!hashtable.ContainsKey(list2[i]))
                    {
                        hashtable.Add(list2[i], list2[i]);
                        AntiSearchResult item = new AntiSearchResult {
                            searchType = searchType,
                            keyWord = keyword,
                            searchCondition = searchCondition,
                            tradePublishId = this.tradePublishId
                        };
                        item.detail[0x11] = list2[i];
                        item.needSaveAntiSearch = true;
                        list.Add(item);
                    }
                }
                this.log.Info("总计：反查获得" + list.Count + "个.");
            }
            return list;
        }

        private string[] GetDetial(string source)
        {
            string[] strArray = new string[0x17];
            string inName = "";
            string str2 = "";
            string str3 = "";
            string str4 = "";
            string str5 = "";
            string str6 = "";
            string str7 = "";
            string str8 = "";
            string str9 = "";
            string str10 = "";
            string str11 = "";
            string str12 = "";
            string str13 = "";
            string str14 = "";
            string str15 = "";
            string str16 = "";
            string str17 = "";
            source = source.Substring(source.IndexOf("国际分类号") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            inName = source.Substring(0, source.ToLower().IndexOf("</td"));
            inName = this.RemoveCode(inName).Replace(" ", "");
            source = source.Substring(source.IndexOf("申请日期") + 10);
            source = source.Substring(source.IndexOf(">") + 1);
            str2 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str2 = this.RemoveCode(str2).Replace(" ", "");
            source = source.Substring(source.IndexOf("申请人名称(中文)") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str3 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str3 = this.RemoveCode(str3).Replace(" ", "");
            source = source.Substring(source.IndexOf("申请人地址(中文)") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str4 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str4 = this.RemoveCode(str4);
            source = source.Substring(source.IndexOf("申请人名称(英文)") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str5 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str5 = this.RemoveCode(str5);
            source = source.Substring(source.IndexOf("申请人地址(英文)") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str6 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str6 = this.RemoveCode(str6);
            source = source.Substring(source.IndexOf("服务列表") + 15);
            source = source.Substring(source.ToLower().IndexOf("javascript:window.open") + 0x18);
            str7 = source.Substring(0, source.IndexOf("'")).Replace("&amp;", "&");
            source = source.Substring(source.IndexOf("初审公告期号") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str8 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str8 = this.RemoveCode(str8).Replace(" ", "");
            source = source.Substring(source.IndexOf("注册公告期号") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str10 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str10 = this.RemoveCode(str10);
            source = source.Substring(source.IndexOf("初审公告日期") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str9 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str9 = this.RemoveCode(str9).Replace(" ", "");
            source = source.Substring(source.IndexOf("注册公告日期") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str11 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str11 = this.RemoveCode(str11).Replace(" ", "");
            source = source.Substring(source.IndexOf("专用权期限") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str12 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str12 = this.RemoveCode(str12).Replace(" ", "");
            source = source.Substring(source.IndexOf("代理人名称") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str13 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str13 = this.RemoveCode(str13);
            source = source.Substring(source.IndexOf("商标类型") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str15 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str15 = this.RemoveCode(str15);
            source = source.Substring(source.IndexOf("是否共有商标") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            if (source.Substring(0, source.ToLower().IndexOf("</td")).IndexOf("查看共有人") > 0)
            {
                str14 = "是";
            }
            else
            {
                str14 = "否";
            }
            source = source.Substring(source.IndexOf("备注") + 15);
            source = source.Substring(source.IndexOf(">") + 1);
            str17 = source.Substring(0, source.ToLower().IndexOf("</td"));
            str17 = this.RemoveCode(str17).Replace("\\\"", "\"");
            str17 = str17.Substring(str17.IndexOf(">") + 1);
            if (str17.ToLower().IndexOf("</font") > 0)
            {
                str17 = str17.Substring(0, str17.ToLower().IndexOf("</font"));
            }
            else
            {
                str17 = "";
            }
            source = source.Substring(source.ToLower().IndexOf("商标流程") + 15);
            source = source.Substring(source.ToLower().IndexOf("javascript:window.open") + 0x18);
            str16 = source.Substring(0, source.ToLower().IndexOf("'")).Replace("&amp;", "&");
            source = "";
            strArray[0] = inName;
            strArray[1] = str2;
            strArray[2] = str3;
            strArray[3] = str4;
            strArray[4] = str5;
            strArray[5] = str6;
            strArray[6] = str7;
            strArray[7] = str8;
            strArray[8] = str9;
            strArray[9] = str10;
            strArray[10] = str11;
            strArray[11] = str12;
            strArray[12] = str13;
            strArray[13] = str14;
            strArray[14] = str15;
            strArray[15] = str16;
            strArray[0x10] = str17;
            return strArray;
        }

        private CookieContainer getLoginCookie()
        {
            CookieContainer container = null;
            GraspHTML phtml = new GraspHTML();
            container = phtml.getLoginCookie(Global.LoginURL);
            if (phtml.getException().Length > 0)
            {
                container = null;
            }
            return container;
        }



        private List<string> getRegNos(int intCls, int searchType, string keyword, string searchConditionCode)
        {
            if (searchType == 2)
            {
                keyword = "%" + ToHex(keyword, "gb2312", true);
            }
            List<string> rtn = new List<string>();

            #region 完全相同是在45类内
            for (int i = 1; i <= 45; i++)
            {
                Int32 linkIntCls = intCls;
                if (searchConditionCode.Equals("01"))
                {
                    //完全相同
                    linkIntCls = i;
                }
                else if(i >1)
                {
                    break;

                }
            #endregion
            #region//关联类内
                //for (int i = 0; i < 6; i++)
                //{
                //    Int32 linkIntCls = Global.categoryOOlink[intCls - 1, i];
                //if (!searchConditionCode.Equals("01") && i > 0)
                //{
                //    break;
                //}
                //else if (linkIntCls == 0)
                //{
                //    continue;
                //}
                #endregion
                
                String trueUrl = Global.antiSearchUrl.Replace("${0}", "" + linkIntCls).Replace("${1}", keyword).Replace("${2}", searchConditionCode);
                if (searchType == 0)
                {
                    trueUrl = trueUrl.Replace("SearchMode=Word", "SearchMode=English");
                }
                else if (searchType == 1)
                {
                    trueUrl = trueUrl.Replace("SearchMode=Word", "SearchMode=Num");
                }


                //http://sbcx.saic.gov.cn/trade/servlet?Search=SX_Reg&SelectContent=&IntCls=1&QunCode=&Content=%bc%ce%d4%b4&SearchMode=Word&selectClass=07;
                //查询到的页数共：1页
                //http://sbcx.saic.gov.cn/trade/SelectReg/ResultReg.jsp?pCount=3 //后面的页码



                //采集第一页,先不采集后续的页面了。 
                while (true)
                {
                    try
                    {
                        log.Info("开始反查商标[intCls=" + linkIntCls + ",searchType=" + searchType + ",keyword=" + keyword + ",searchConditionCode=" + searchConditionCode + "]");
                        if (logc == null)
                        { //登录首页
                            log.Info("访问商标局首页:url=http://sbcx.saic.gov.cn/trade/index.jsp");
                            this.logc = getLoginCookie();
                        }
                        if (this.logc == null)
                        {
                            Thread.Sleep(1000);
                            log.Info("反查商标，登录异常"); //---------登录失败，抛出异常，结束。 
                            continue;
                        }
                        #region  开始反查，获得html代码
                        GraspHTML grasphtml = new GraspHTML();
                        String source = grasphtml.getHTMLCode(trueUrl, this.logc);
                        if (source == null || source.Equals("") || source.IndexOf("查询到的页数共：") < 0)
                        {
                            Thread.Sleep(1000);
                            log.Info("反查商标，获得的html[url=" + trueUrl + "]错误,需要从首页访问."); //---------登录失败，抛出异常，结束。
                            this.logc = getLoginCookie();
                            continue;
                        }
                        #endregion

                        #region 获得全部注册号
                        Parser parserT = Parser.CreateParser(source, "UTF-8"); ;
                        NodeFilter filterT = new NodeClassFilter(typeof(Winista.Text.HtmlParser.Tags.ATag));
                        NodeList nodesT = parserT.ExtractAllNodesThatMatch(filterT);

                        Hashtable rHt = new Hashtable();
                        string rN = "";

                        for (int j = 0; j < nodesT.Size(); j++)
                        {
                            Winista.Text.HtmlParser.Tags.ATag tag = (Winista.Text.HtmlParser.Tags.ATag)(nodesT.ElementAt(j) is ITag ? nodesT.ElementAt(j) as ITag : null);
                            if (tag != null && !tag.IsEndTag())
                            {
                                rN = tag.GetAttribute("onclick");//javascript:window.open('/trade/servlet?Search=SX_TIReg&amp;RegNO=119748&amp;IntCls=30&amp;iYeCode=0','','width=700 height=710 left=160 top=0 scrollbars=1 resizable=1');" style="cursor:hand;" href="javascript:void(null)

                                MatchCollection mc = Regex.Matches(rN, @"open\('/trade/servlet\?Search=SX_TIReg&amp;RegNO=[^']+'", RegexOptions.IgnoreCase);
                                foreach (Match mt in mc)
                                {
                                    rN = mt.Value.Substring("open('/trade/servlet?Search=SX_TIReg&amp;RegNO=".Length, 17);
                                    rN = rN.Substring(0, rN.IndexOf("&"));
                                    if (!rHt.Contains(rN) && !regNo.Equals(rN))
                                    {
                                        rHt.Add(rN, rN);
                                    }
                                    break;
                                }
                            }
                        }
                        foreach (System.Collections.DictionaryEntry item in rHt)
                        {
                            rtn.Add(item.Key.ToString());
                        }
                        #endregion

                        break;
                    }
                    catch (Exception e)
                    {
                        log.Error("反查商标，异常.", e);
                        Thread.Sleep(1000);
                        continue;
                    }
                }
            }
            log.Info("开始反查商标[关联分类内：searchType=" + searchType + ",keyword=" + keyword + ",searchConditionCode=" + searchConditionCode + "] 获得商标" + rtn.Count + "个");
            return rtn;
        }


        

        private string RemoveCode(string inName)
        {
            if ((inName != null) && (inName.Length > 0))
            {
                inName = inName.Replace("\r", "");
                inName = inName.Replace("\n", "");
                inName = inName.Replace("\t", "");
                inName = inName.Replace("&nbsp;", " ");
            }
            return inName;
        }

        private string saveTMImage(string pageUrlAll, CookieContainer cc, string classNum, string regno)
        {
            string str = "";
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                request = (HttpWebRequest) WebRequest.Create(pageUrlAll);
                request.CookieContainer = cc;
                response = request.GetResponse() as HttpWebResponse;
                Image image = Image.FromStream(response.GetResponseStream());
                image.RotateFlip(RotateFlipType.Rotate180FlipX);
                image.Dispose();
                response.Close();
            }
            catch (Exception exception)
            {
                str = exception.Message.ToString();
            }
            finally
            {
                response.Close();
                request = null;
                response = null;
            }
            return str;
        }

        

        public static string ToHex(string s, string charset, bool fenge)
        {
            byte[] bytes = Encoding.GetEncoding(charset).GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str = str + string.Format("{0:X}", bytes[i]);
                if (fenge && (i != (bytes.Length - 1)))
                {
                    str = str + string.Format("{0}", "%");
                }
            }
            return str.ToLower();
        }
    }
}

